//
//  MessageViewController.m
//  TinyFortune
//
//  Created by lc on 16/6/3.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "MessageViewController.h"
#import "Communication.h"
#import "MessageCell.h"
#import "MessageModel.h"
#import "AVFile +  getDictionary.h"
#import "bigPicViewController.h"
#define page2 6
NSString *const messageCellIdentifier = @"messageCell";

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource>

//tableView三件套
@property (nonatomic,strong) UITableView *messageTable ;
@property (nonatomic,strong) NSMutableArray *dataArray ;


@end

@implementation MessageViewController
#pragma mark - 懒加载
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return  _dataArray ;
}
- (NSMutableArray *)messageArray{
    if (!_messageArray) {
        _messageArray = [NSMutableArray new];
    }
    return _messageArray;
}
#pragma mark - 首次加载
- (void)firstLoad{
    __weak typeof(self)weakSelf = self;
    //从服务器取到所有数据
    self.currentPage = 1 ;
    AVQuery *query = [AVQuery queryWithClassName:@"message" ];
    if (![AVUser currentUser]) {
        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"亲还没登录呢" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
        [view show];
    }
    
    else{
        [query whereKey:@"ID" equalTo:[AVUser currentUser].mobilePhoneNumber ];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        weakSelf.messageArray = [NSMutableArray arrayWithArray:objects];
        [weakSelf sortArray:self.messageArray];
        [weakSelf requestDataWithCurrentPage:weakSelf.currentPage];
        }];
    }
}
#pragma mark -排序
//按时间排序，最先发布的在最上面
- (void)sortArray:(NSMutableArray *)mArray{
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO];
    [mArray sortUsingDescriptors:@[sort]];
}
#pragma mark - 界面搭建
- (void)createUI{
    //tableView
    _messageTable = [UITableView new];
    [self.view addSubview:_messageTable];
    __weak typeof(self)weakSelf = self;
    [_messageTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    _messageTable.delegate = self ;
    _messageTable.dataSource = self ;
    _messageTable.backgroundColor = [UIColor whiteColor];
    [_messageTable registerNib:[UINib nibWithNibName:@"MessageCell" bundle:nil] forCellReuseIdentifier:messageCellIdentifier];
    //添加上拉刷新和下拉加载
    _messageTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _messageTable.mj_footer.hidden = YES ;
        [self firstLoad];
    }];
    _messageTable.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        //隐藏header
        _messageTable.mj_header.hidden = YES;
        self.currentPage ++ ;
        [weakSelf requestDataWithCurrentPage:self.currentPage];
        
    }];

}
#pragma mark - tableView协议
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataArray.count ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:messageCellIdentifier forIndexPath:indexPath];
        AVQuery *query =[AVQuery queryWithClassName:@"_User"];
        [query whereKey:@"lovers" equalTo:[AVUser currentUser].mobilePhoneNumber];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (objects.count > 0) {
                AVUser *loveUser = objects.firstObject;
                NSDictionary *dicc = [AVFile fileWithDictionary:[loveUser objectForKey:@"iconImage"] ];
                
                NSDictionary *dict = @{@"name":loveUser.username,
                                       @"url":dicc[@"url"]
                                       };
                MessageModel *model = [[MessageModel alloc]initWithDict:dict];
                cell.model = model;
            }else{
                MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:messageCellIdentifier forIndexPath:indexPath];
                NSDictionary *dict = @{@"name":@"还未添加情侣"};
               MessageModel *model = [[MessageModel alloc]initWithDict:dict];
                cell.model = model ;
            }
           

        }];
      
              return  cell ;
    }else{
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:messageCellIdentifier forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.row - 1];
    return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        if ([[AVUser currentUser]objectForKey:@"lovers"]) {
        
        Communication *com = [Communication new];
        [com setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:com animated:YES];
        }else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"您还未添加情侣,无法发送" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alertView show];
        }
    }else{
        bigPicViewController *big = [bigPicViewController new];
        AVObject *tObj = self.messageArray[indexPath.row-1 ];
        big.objectID = [tObj valueForKey:@"talkID"];
        [big setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:big animated:YES];
    }
}
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self firstLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -数据相关
- (void)requestDataWithCurrentPage:(NSInteger)currentPage{
    //模拟一个通过页数来控制刷新个数的方法
    int temp = (self.currentPage - 1) *page2 ;
    for (int i = temp ; i <self.currentPage * page2 && i < self.messageArray.count ; i++) {
        [self requestDataWithObject:self.messageArray[i]];
        NSLog(@"%ld",(unsigned long)self.messageArray.count);
    }
}

- (void)requestDataWithObject:(AVObject *)object{
        __weak typeof(self)weakSelf = self ;
    
    MessageModel *model = [[MessageModel alloc]initWithObject:object];
    if (self.currentPage == 1 && weakSelf.dataArray.count >= 6) {
        [self.dataArray removeAllObjects];
    }

    [self.dataArray addObject:model];
    //刷新视图
  dispatch_async(dispatch_get_main_queue(), ^{
      [weakSelf.messageTable reloadData];
      [weakSelf.messageTable.mj_header endRefreshing];
      [weakSelf.messageTable.mj_footer endRefreshing];
      weakSelf.messageTable.mj_footer.hidden = NO;
      weakSelf.messageTable.mj_header.hidden = NO;
      // 处理全部加载完成的情况
      if (weakSelf.messageArray.count <= weakSelf.dataArray.count) {
          //数据全部请求完毕
          [weakSelf.messageTable.mj_footer endRefreshingWithNoMoreData];
      }//当你数据还不够多时，重置footer的状态
      else{
          [weakSelf.messageTable.mj_footer resetNoMoreData];
      }

      
  });
    
}

@end
